const app = getApp()
let text = require('../../../common/util/text.js')
let util = require('../../../common/util/util.js')
// import * as echarts from '../../../ec-canvas/echarts';
Page({
    data: {
        animation_class:'',
        xPageReady : 'start' ,
        first:0,
        user: [
          { cn: '让我了解你的身份', key: 'standing', value: '', type: 'pickerValue', range: ["患者本人", "患者家属"] },
          { cn: '患者年龄', key: 'age', value: '', type: 'text'},
          { cn: '你的疼痛问题持续多久了？', key: 'pain_persistence_duration', value: '', type: 'pickerText', range: ["不超过6个月", "6个月～1年", "1年～3年", "3年～5年","超过5年"] },
          { cn: '你的平均疼痛程度大概是如何？', key: 'average_pain_level', value: '', type: 'pickerIndex', range: ["无痛", "轻微疼痛，可以忍受，不影响睡眠", "中度疼痛，不能忍受，影响睡眠", "重度疼痛，严重影响生活和睡眠","剧痛无比"] },
          { cn: '你是否有抑郁、焦虑的情绪困扰？', key: 'emotional_disturbance', value: '', type: 'pickerIndex', range: ["一点也没有", "有轻微情绪困扰", "中度情绪困扰", "严重情绪困扰"] },
          { cn: '疼痛问题是否对你的工作生活造成影响?', key: 'work_life_impact', value: '', type: 'pickerIndex', range: ["一点也没有", "轻微影响", "中度影响", "严重影响"]},
          { cn: '你是否有睡眠困扰？', key: 'sleep_disturbance', value: '', type: 'pickerIndex', range: ["一点也没有", "轻微失眠", "较严重失眠"]},
          { cn: '你是否感觉自己再也无法忍受这种痛苦了?', key: 'unbearable', value: '', type: 'pickerIndex', range: ["从来没有", "偶尔", "有时候这么想", "经常性这么想","总是这么想"]},
          { cn: '为了解决疼痛问题，大概花费了多少钱？', key: 'treatment_cost', value: '', type: 'pickerText', range: ["不超过2千元", "2千元～5千元", "5千元～1万元", "1万以上"]},

          { cn: '患者姓名', key: 'real_name', value: '', type: 'textarea'}, // 真实姓名
          { cn: '手机号', key: 'phone_number', value: '', type: 'phone'},
          { cn: '选择你的主治医生', key: 'doctor_id', value: '', type: 'pickerDoctor'}
        ],
        userInfo:{},
        levelList:[{name:'无痛',bgColor:'#95F204'},
          {name:'轻微疼痛',bgColor:'#F8B967'},
          {name:'中度疼痛',bgColor:'#F59A23'},
          {name:'重度疼痛',bgColor:'#E55063'},
          {name:'剧痛无比',bgColor:'#D9001B'}
        ],
        needSetting:app.globalData.needAuthorization
        // ec: {
        //   lazyLoad: true,
        // },
    },
    onLoad: function (options) {
      let that =this
      if(options.hospital_id){
        that.xLogin(options)
      }else{
        that.xInit()
      }
      // that.xInitCanvas()
    },
    xChildReload: function () {
      var pages = getCurrentPages();//当前页面栈
      if (pages.length > 1) {
        var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
        if(beforePage.data.xProductnew){
          beforePage.xInfo()
        }
      }
    },
    xToBack:function(e){
      let that =this
      let index = e.currentTarget.dataset.index
      let step = e.currentTarget.dataset.step
      that.setData({
        first:step,
        animation_class: 'animation_class_before'
      })
      wx.pageScrollTo({
        scrollTop: 0,
      })
    },
    xToStep:function(e){
      let that =this
      let index = that.data.first
      let step = that.data.first+1
      if( that.data.user[index].value ==='' || that.data.user[index].value.length==0 ){
        wx.showToast({
          title: '当前内容未填写，请检查',
          icon:'none'
        })
        return
      }
      if(step < that.data.user.length){
        setTimeout(function(){
          that.setData({
            first:step,
            animation_class: 'animation_class'
          })
          wx.pageScrollTo({
            scrollTop: 0,
          })
        },100)
      }
    },
    xLogin:function(obj){
      let that = this
      wx.cloud.callFunction({
        name: "user",
        data: {
          action: "login",
          userInfo: obj
        },
        success: function (res) {
          app.globalData.user = res.result
          app.globalData.xCustomer = res.result
          that.xInit()
        }
      })
    },
    xToStart:function(){
      let that = this
      that.setData({
        xPageReady:'going'
      })
    },
    xInit:function () {
        let that = this
         wx.cloud.callFunction({
            name: "user",
            data: {
                action: "detail"
            }
        }).then(res => {
            that.setData({
              userInfo:res.result
            })
            for(let index in that.data.user){
              if(that.data.user[index].key== 'doctor_id'){
                that.setData({
                  [`user[${index}].value`]: res.result.doctor_id?res.result.doctor_id:''
                }) 
              }
            }
            that.xGetDoctor(res.result.hospital_id)
        })
    },
    xGetDoctor:function(id){
      let that = this
      wx.cloud.callFunction({
        name: 'doctors',
        data: {
          action: "get_doctor_by_hospital",
          hospital_id:id
        }
      }).then(res => {
        that.setData({
          doctorList:res.result
        })
      })
    },
    xInput: function (e) {
        let that = this
        let value = e.detail.value
        let params = e.currentTarget.dataset
        that.setData({
            [`user[${params.idx}].value`]: value
        })
    },
    choose:function(e){
      let that = this
      let params = e.currentTarget.dataset
      that.setData({
        [`user[${params.idx}].value`]: params.value
      })
      that.xToStep()
    },
    handleTouchInput:function(){
      this.setData({
        innerShow:true
      })
    },
    changePrivacySetting:function(e){
      this.setData({
        needSetting:false
      })
    },
    xPhone: async function (e) {
        let that = this
        let params = e.currentTarget.dataset
        wx.showLoading({
            title: '请稍等',
        })
        await wx.cloud.callFunction({
            name: 'user',
            data: {
                action: 'getPhone',
                cloudID: e.detail.cloudID
            },
            success: function (res) {
                that.setData({
                    [`user[${params.idx}].value`]: res.result.phoneNumber
                })
                that.xToStep()
            }
        })
        wx.hideLoading()
    },
    xSubmit: function () {
        let that = this
        let user = that.data.user
        let key =0
        for (let i in that.data.user) {
          if (that.data.user[i].value === ''  && that.data.user[i].step== that.data.first || that.data.user[i].value.length==0  && that.data.user[i].step== that.data.first) {
              key=key+1
          }
        }
        if(key>0){
          var firstQ = ''
          for (var i =0;i<that.data.user.length;i++) {
            if (that.data.user[i].value === '') {
              firstQ=i
              break;
            }
          }
          wx.showModal({
            title: "提示",
            content: "请确保所有内容填写正确，当前有"+ key +"项内容未填写，请检查！",
            showCancel: false,
            confirmText:'好的',
            success (res) {
              if (res.confirm) {
                wx.pageScrollTo({
                  selector: '#selector'+firstQ,
                })
              }
            }
          })
          return
        }
        wx.showLoading({
          title: '保存中',
        })
        that.xUpload(user)
    },
    xUpload: function (data) {
        let that =this;
        let form = {}
        let resultList = that.data.resultList
        for (var i = 0; i < data.length; i++) {
            if (data[i].value !== '') {
                form[data[i].key] = data[i].value
            }
        }
        wx.cloud.callFunction({
            name: "evaluation",
            data: {
                action: "add_previewing_scale",
                params: form
            }
        }).then(res => {
          wx.hideLoading()
          res.result.create_time = util.formatDate(new Date(res.result.create_time))
          res.result.desc = text.text(res.result.desc)
          that.setData({
            xPageReady:'end',
            result:res.result
          })
          that.xChildReload()
          // that.xInitCanvas()
          
        })
    },
    xChat:function(){
      let that =this;
      var url= 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/zxs_QR.png?time='+Date.now() //地址加上时间戳，否则从缓存中加载
      wx.previewImage({
        urls: [url],
      })
    },
    // xInitCanvas:function(){
    //   let that =this;
    //   that.setData({
    //     show:true
    //   })
    //   console.log(1)
    //   that.ecComponent = that.selectComponent('#mychart-dom-graph');
    //   that.ecComponent.init((canvas, width, height, dpr) => {
    //     const chart = echarts.init(canvas, null, {
    //       width: width,
    //       height: height,
    //       devicePixelRatio: dpr // new
    //     });
    //     chart.setOption({
    //       radar: [
    //         {
    //           indicator: [
    //             { text: 'Brand', max: 100 },
    //             { text: 'Content', max: 100 },
    //             { text: 'Usability', max: 100 },
    //             { text: 'Function', max: 100 }
    //           ],
    //           center: ['25%', '40%'],
    //           radius: 80
    //         }
    //       ],
    //       series: [
    //         {
    //           type: 'radar',
    //           tooltip: {
    //             trigger: 'item'
    //           },
    //           areaStyle: {},
    //           data: [
    //             {
    //               value: [60, 73, 85, 40],
    //               name: 'A Software'
    //             }
    //           ]
    //         }
    //       ]
    //     });
    //     canvas.setChart(chart);
    //     return chart;
    //   });
    // },
    xToResearch:function(){
      wx.redirectTo({
        url: '/subuser/pages/research/index?type=choosePlan',
      })
    },
    xBack:function(){
      wx.reLaunch({
        url: '/pages/navigation/using/index',
      })
    },
})